package weibo.web;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import weibo.DecodeWeiboCaptcha;
import weibo.WeiboCrackerUtils;

public class CaptchaManualServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String url = "";
		String cpt = "";
		int count = 1;
		while (!cpt.startsWith("2_")) {
			url =  getCaptchaUrl();
			String[] s = url.split("=");
			cpt = s[1];
			System.out.println("this is the "+count+ " time to get a pic" );
			count++;
		}
		URL uri = new URL(url);
		BufferedImage img = ImageIO.read(uri.openStream());

		DecodeWeiboCaptcha.cleanImage(img);
		List<BufferedImage> list = DecodeWeiboCaptcha.getListSub(img);
		String text = "";
		if (list.size() == 5){
			
			for(int i=0; i< list.size(); i++){
				String filename = getServletContext().getRealPath("/")+"/"+(i+1)+".png";
				File outputfile = new File(filename);
				ImageIO.write(list.get(i), "png", outputfile);
				try {
					text = text + WeiboCrackerUtils.getMostSimilarLetter(list.get(i));
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			req.setAttribute("message", "right on");
			req.setAttribute("text", text);
		} else{
			req.setAttribute("message", "something goes wrong, please skip it.");
			req.setAttribute("text", "FO");
		}
		
		String[] s = url.split("=");
		req.setAttribute("url",url);
		req.setAttribute("cpt", s[1]);
		
		this.getServletContext().getRequestDispatcher("/WEB-INF/jsp/decode.jsp").forward(req, resp);
	}

	private String getCaptchaUrl() {
//		HttpHost proxy = new HttpHost("connsvr.nike.com",8080);
		HttpClient httpClient = new DefaultHttpClient();
		
//		httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy);
		
		HttpUriRequest httpUriRequest = new HttpGet("http://3g.sina.com.cn/prog/wapsite/sso/register.php?backURL=http%3A%2F%2Fweibo.cn%2F&backTitle=%D0%C2%C0%CB%CE%A2%B2%A9&vt=4&revalid=2&ns=1&type=m");
		
		httpUriRequest.setHeader("User-Agent", "Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit/420.1 (KHTML, like Gecko) Version/3.0 Mobile/1A542a Safari/419.3");
		
		httpUriRequest.setHeader("HTTP_VIA", "203.129.72.215");
		httpUriRequest.setHeader("HTTP_X_FORWARDED_FOR", "203.98.182.163");
		
		HttpResponse httpResponse = null;
		try {
			httpResponse = httpClient.execute(httpUriRequest);
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		HttpEntity entity = httpResponse.getEntity();
		String html = null;
		try {
			html = new String(EntityUtils.toString(entity).getBytes());
			
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		Document doc = Jsoup.parse(html);
		String url =  doc.getElementsByTag("img").get(0).attr("src");
		return url;
	}
	
}
